<?php
    //apartment-add.php
    session_start();
    if($_SESSION['uid']==""||$_SESSION['level']!=3){
        header("Location: ../exit.php");
        exit();
    }
    include('/tool/submitValidate.php');
    include('/tool/pdo.php');
    include('/class/apartment.class.php');
    include('/bll/ApartmentBLL.php');

	$name = isset($_POST['name']) ? $_POST['name'] : '';
    $abbreviation = isset($_POST['abbreviation']) ? $_POST['abbreviation'] : '';
    $property = isset($_POST['property']) ? $_POST['property'] : '';
	$height = isset($_POST['height']) ? $_POST['height'] : '';
	$rooms = isset($_POST['rooms']) ? $_POST['rooms'] : '';
	$beds = isset($_POST['beds']) ? $_POST['beds'] : '';
    $remarks  = isset($_POST['remarks']) ? $_POST['remarks'] : '';
    
    $error_array=array();
    // 正整数："/^\+?[1-9][0-9]*$/" 汉字：'~[\x{4e00}-\x{9fa5}]+~u'
    $flag=true;
    /*if (!preg_match("/^\+?[1-9][0-9]*$/",$id)) {
        $error_array[]=0;
        $flag=false;
    }*/
    if(!preg_match('~[\x{4e00}-\x{9fa5}]+~u',$name)){
        $error_array[]=1;
        $flag=false;
    }
    if(utf8_strlen($abbreviation)>10){
        $error_array[]=2;
        $flag=false;
    }
    if(!preg_match("/^\+?[1-9][0-9]*$/",$height)){
        $error_array[]=3;
        $flag=false;
    }
    if(!preg_match("/^\+?[1-9][0-9]*$/",$rooms)){
        $error_array[]=4;
        $flag=false;
    }
    if(!preg_match("/^\+?[1-9][0-9]*$/",$beds)){
        $error_array[]=5;
        $flag=false;
    }
    if(utf8_strlen($remarks)>30){
        $error_array[]=6;
        $flag=false;
    }
    if(!preg_match("/^\+?[1-3]*$/",$property)){
        $flag=false;
    }
    if($flag){
        $apartment=new ApartmentModel();
        //$apartment->apartment_id=$id;
        $apartment->apartment_name=$name;
        $apartment->abbreviation_name=$abbreviation;
        $apartment->property=$property;
        $apartment->floor_number=$height;
        $apartment->remarks=$remarks;
        $apartment->number_of_rooms=$rooms;
        $apartment->beds=$beds;

        $apartmentBLL=new ApartmentBLL();
        $message=$apartmentBLL->addApartment($apartment);
    }else{
        $message=array(
            'code'=>"2002",
            'message'=>$error_array,
            'url'=>"./apartment-add.php"
        );
    }
    // 计算中文字符串长度
    function utf8_strlen($string = null) {
        // 将字符串分解为单元
        preg_match_all("/./us", $string, $match);
        // 返回单元个数
        return count($match[0]);
    }
    echo json_encode($message,JSON_UNESCAPED_UNICODE);
?>